package com.citywithincity.db;

import java.lang.reflect.Field;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import com.citywithincity.db.interfaces.IPsSetter;
import com.citywithincity.db.interfaces.IValueConvert;
import com.citywithincity.db.meta.ColumnStruct;
import com.citywithincity.db.meta.TableStruct;

public class EntityField {

	public EntityField(TableStruct tableStruct,ColumnStruct columnStruct, Field field,int index) {
		columnName = columnStruct.getName();
		this.field = field;
		this.tableStruct = tableStruct;
		this.index  =index;
	}

	
	int index ;
	
	//
	private TableStruct tableStruct;
	//
	private ColumnStruct columnStruct;
	//反射
	Field field;
	//
	IPsSetter psSetter;
	// 数据库出来，到entity的
	private IValueConvert toEntityConvert;
	
	//纯columnName
	String columnName;
	
	public String getColumnName() {
		return columnName;
	}
	public IValueConvert getToEntityConvert() {
		return toEntityConvert;
	}
	public void setToEntityConvert(IValueConvert toEntityConvert) {
		this.toEntityConvert = toEntityConvert;
	}

	

	public Field getField() {
		return field;
	}

	public void setField(Field field) {
		this.field = field;
	}

	public ColumnStruct getColumnStruct() {
		return columnStruct;
	}

	public void setColumnStruct(ColumnStruct columnStruct) {
		this.columnStruct = columnStruct;
	}

	public TableStruct getTableStruct() {
		return tableStruct;
	}


	public Object get(Object entity){
		try {
			return field.get(entity);
		} catch (IllegalArgumentException e) {
			throw new RuntimeException(e);
		} catch (IllegalAccessException e) {
			throw new RuntimeException(e);
		}
	}
	
	
	
	
	public void set(Object entity, Object value) {
		try {
			if(toEntityConvert!=null){
				value  = toEntityConvert.convert(value);
			}
			field.set(entity, value);
		} catch (IllegalArgumentException e) {
			throw new RuntimeException(e);
		} catch (IllegalAccessException e) {
			throw new RuntimeException(e);
		}
	}
	public void setPs(PreparedStatement ps, int index, Object entity) throws SQLException {
		try{
			Object value = field.get(entity);
			psSetter.setValue(ps, index, value);
		}catch(Exception e){
			throw new SQLException(e);
		}
		
	}
	
	

}
